package IntelSpam::Filters::BayesianFilter;

use 1.0;

use warnings;
use IntelSpam::Config;
use IntelSpam::Bayesian;
use Data::Dumper;
use HTML::Scrubber;
use File::Spec;

our $VERSION = '1.0';
our $DEBUG = 1;

our $REGISTER = ['body'];
our $META = {
	'id' => 'bayesian_filter',
	'name' => 'Bayesian Spam Filter',
	'description' => 'Bayesian Filter',
	'version' => '1.0',
	'weight' => 20
	
};

our $ham_file = 'ham.txt';
our $spam_file = 'spam.txt';
our $is_train = 0;

our $CFG = {};
our @bad_words = ();

sub new($){
	bless {}, shift;
}

sub filter_header($$$$){
	my ($this, $ctx, $key, $value) = @_;

	if(lc($key) ne 'subject'){
		return 0;
	}
	my $conf = $CFG->getcfg($META->{'id'});
	my $score = bayesian_filter($value, $is_train, $spam_file, $ham_file);
	if($score >= 0.5){
		$score *= $META->{'weight'};
	}else{
		$score *= $META->{'weight'} * 0.49;
	}
	
	$ctx->getpriv()->{'score'}->insert($META->{'id'}, $META->{'weight'}, $score);

}
sub filter_body($$$){
	my ($this, $ctx, $entity) = @_;
	find_html($ctx, $entity);
}

sub find_html {
    my ($ctx, $entity, $name) = @_;
    defined($name) or $name = "'anonymous'";
    my $IO;


    # Output the body:
    my @parts = $entity->parts;
    if (@parts) {                     # multipart...
	my $i;
	foreach $i (0 .. $#parts) {       # dump each part...
	    find_html($ctx, $parts[$i], ("$name, part ".(1+$i)));
	}
    }
    else {                            # single part...	
	my $conf = $CFG->getcfg($META->{'id'});
	# Get MIME type, and display accordingly...
	if($entity->head->mime_type =~ /^text\/\w*html$/i){
		$contents = $entity->body_as_string;
		my $scrubber = HTML::Scrubber->new;
		$plain_text = $scrubber->scrub($contents);
		my $score = bayesian_filter($plain_text, $is_train, $spam_file, $ham_file);
		$score *= $META->{'weight'};
		$ctx->getpriv()->{'score'}->insert($META->{'id'}, $META->{'weight'}, $score);
	}elsif($entity->head->mime_type =~ /^text\/plain/i){
		$contents = $entity->body_as_string;

		my $score = bayesian_filter($contents, $is_train, $spam_file, $ham_file);
		$score *= $META->{'weight'};
		$ctx->getpriv()->{'score'}->insert($META->{'id'}, $META->{'weight'}, $score);
	}
    }
}

sub get_registers($){
	$REGISTER;
}

sub get_meta($){
	$META;
}

sub set_cfg($$){

	my $this = shift;
	$CFG = shift;
	my $conf = $CFG->getcfg($META->{'id'});
	
	
	$ham_file = File::Spec->catfile($conf->{'store'}, 'ham.txt');
	$spam_file = File::Spec->catfile($conf->{'store'}, 'spam.txt');
	if(defined $conf->{'train'} && $conf->{'train'} eq 'true'){
		$is_train = 1;
	}	
	loadGoodWords($ham_file);
	loadBadWords($spam_file);
}

1;

